<template>
  <xDialog v-model="isShow" width="550px" @open="handleOpen" @closed="handleClose" :title="modalTitle">
    <el-form :model="formData" :rules="rules" ref="formRef">
      <el-form-item label="用户姓名" prop="username">
        <el-input placeholder="请您输入用户姓名" v-model="formData.username"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="name">
        <el-input placeholder="请您输入用户昵称" v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="用户密码" prop="password" v-if="!formData.id">
        <el-input placeholder="请您输入用户密码" v-model="formData.password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </xDialog>
</template>

<script setup lang="ts">
import { ref, computed, defineEmits, defineProps } from 'vue'
import useDialog from '@/hooks/dialog'
// import xDialog from '@/components/x-dialog/index.vue'
import { ElMessage } from 'element-plus'
import { reqAddOrUpdateUser } from '@/api/acl/user'
const emit = defineEmits(['undated'])
const modalTitle = computed(() => (props.modalType === 'edit' ? '编辑用户' : '添加用户'))
const props = defineProps({
  modalData: { required: false, type: Object, default: () => {} },
  modalType: { required: false, type: String, default: 'add' }
})
const form = {
  username: '',
  name: '',
  password: ''
}
let formRef = ref()
const { formData, isShow, cancel, open, handleOpen, handleClose } = useDialog({
  formRef: formRef,
  props: props,
  form: form
})
const save = async () => {
  await formRef.value.validate()
  let result: any = await reqAddOrUpdateUser(formData.value)
  if (result.code === 200) {
    emit('undated')
    isShow.value = false
    //提示消息
    ElMessage({ type: 'success', message: formData.value.id ? '更新成功' : '添加成功' })
  } else {
    ElMessage({ type: 'error', message: formData.value.id ? '更新失败' : '添加失败' })
  }
}

//校验用户名字回调函数
const validatorUsername = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
//校验用户名字回调函数
const validatorname = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
const validatorPassword = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
//表单校验的规则对象
const rules = {
  //用户名字
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  //用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
  //用户的密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }]
}
defineExpose({
  open
})
</script>

<style scoped lang="scss"></style>
